//地图类
const QQMapWX = require('./qqmap-wx-jssdk.min.js');
import { config } from './config'
import wepy from 'wepy'
import { china_city } from '../database/china_city.js'

class Address {

  constructor() {
    //实例化地图类
    this.map = new QQMapWX({ key: config.map_key });
  }

  getLocation() {
    return new Promise((resolve, reject) => {
      wepy.getLocation({
        type: 'wgs84',
        success: res => { resolve(res) },
        fail: err => { reject(err) }
      }); 
    })
  }

  //根据经纬度解析地址
  getAddr(latitude, longitude) {
    return new Promise((resolve, reject) => {
      this.map.reverseGeocoder({
        location: { latitude, longitude },
        success: res => {
          resolve(res)
        },
        fail: err => reject(err)
      })
    })
  }
  //筛选出城市对象
  getCityName(city){
    for( let i of china_city ){
      if( i.name === city ) return i
    }
  }
  //设置addr给全局store
  setAddr(cb) {
    this.getLocation()
      .then(res => {
        const { latitude, longitude } = res;
        return this.getAddr(latitude, longitude)
      })
      .then(res=>{
        const city = res.result.ad_info.city;
        const city_obj = this.getCityName(city);
        wepy.$store.dispatch({ type : 'CITY' , payload :city_obj})
        cb()
      })
      .catch(err => {
        //地理位置授权失败
        console.log(err)
      })
  }
}

const mapClass = new Address();

export { mapClass }
